<template>
  <div class="orders-container">
    <div class="header">
      <span class="title">确认订单</span>
      <div class="header-actions">
        <button class="create-order-btn" @click="goToCreateOrder">创建订单</button>
        <button class="test-rabbitmq-btn" @click="testRabbitMQ">测试队列</button>
        <button class="test-page-btn" @click="goToTestPage">测试页面</button>
      </div>
    </div>

    <!-- 地址块 -->
    <div class="address-card" @click="openAddressDialog">
      <div class="addr-left">
        <div class="row"><span class="label">收货人</span><b>{{ address.name || '请填写收货人' }}</b><span class="phone">{{ address.phone || '' }}</span></div>
        <div class="row small"><span class="label">收货地址：</span><span>{{ address.detail || '请填写收货地址' }}</span></div>
      </div>
      <div class="addr-right">></div>
    </div>

    <div v-if="loading" class="hint">加载中...</div>
    <div v-else-if="orders.length === 0" class="hint">暂无订单</div>
    <div v-else class="list">
      <div class="order" v-for="od in orders" :key="od.order_no">
        <div class="order-head">
          <label class="check">
            <input type="checkbox" :value="od.order_no" v-model="selectedNos" />
            <span class="fake"></span>
          </label>
          <span class="no">订单号：{{ od.order_no }}</span>
          <span class="amount">合计 ¥{{ od.total_amount }}</span>
          <span v-if="od.status === 0" class="countdown">剩余 {{ getRemaining(od) }}</span>
        </div>
        <div class="items">
          <div class="item" v-for="it in od.items" :key="it.goods_id + '-' + it.name">
            <img class="cover" :src="it.image_url" />
            <div class="meta">
              <div class="name">{{ it.name }}</div>
              <div class="row">
                <span>¥{{ it.price }}</span>
                <span>x{{ it.qty }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="order-foot">创建时间：{{ new Date(od.created_at).toLocaleString() }}</div>
      </div>
    </div>

    <!-- 配送方式 -->
    <div class="panel">
      <div class="panel-head">
        <span>配送方式</span>
        <span class="gray">快递：包邮</span>
      </div>
    </div>

    <!-- 默认页面不显示支付方式，点击提交订单后在弹窗中选择 -->

    <!-- 底部结算条 -->
    <div class="settle-bar">
      <div class="left">共 {{ selectedItemsCount }} 件商品  小计：<b>¥{{ selectedTotal }}</b></div>
      <button class="submit-btn" @click="submitSelected">提交订单</button>
    </div>

    <!-- 地址编辑弹窗 -->
    <div class="dialog-mask" v-if="addrDialogVisible" @click.self="addrDialogVisible=false">
      <div class="dialog">
        <div class="dialog-title">编辑收货地址</div>
        <div class="dialog-body">
          <div class="form-row">
            <label>收货人</label>
            <input v-model="addressForm.name" placeholder="姓名" />
          </div>
          <div class="form-row">
            <label>手机号</label>
            <input v-model="addressForm.phone" placeholder="手机号" />
          </div>
          <div class="form-row">
            <label>详细地址</label>
            <textarea v-model="addressForm.detail" placeholder="省市区 + 详细地址"></textarea>
          </div>
        </div>
        <div class="dialog-actions">
          <button class="btn" @click="addrDialogVisible=false">取消</button>
          <button class="btn primary" @click="saveAddress">保存</button>
        </div>
      </div>
    </div>

    <!-- 支付确认弹窗 -->
    <div class="dialog-mask" v-if="payDialogVisible" @click.self="payDialogVisible=false">
      <div class="dialog">
        <div class="dialog-title">确认订单</div>
        <div class="dialog-body">
          <div class="summary-row">
            <span>共 {{ selectedItemsCount }} 件</span>
            <span>合计 ¥{{ selectedTotal }}</span>
          </div>
          <div class="summary-row small">
            <span>收货人：{{ address.name || '未填写' }}</span>
            <span>{{ address.phone || '' }}</span>
          </div>
          <div class="summary-row small">
            <span>地址：{{ address.detail || '未填写' }}</span>
          </div>
          <div class="pay-row">
            <label class="radio">
              <input type="radio" value="wechat" v-model="paymentMethodDialog" />
              <span class="dot"></span>
              <span>微信支付</span>
            </label>
          </div>
          <div class="pay-row">
            <label class="radio">
              <input type="radio" value="alipay" v-model="paymentMethodDialog" />
              <span class="dot"></span>
              <span>支付宝</span>
            </label>
          </div>
        </div>
        <div class="dialog-actions">
          <button class="btn" @click="payDialogVisible=false">取消</button>
          <button class="btn primary" @click="confirmPay">提交订单</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import orderService from '@/api/order-fixed'

const orders = ref([])
const loading = ref(false)
const selectedNos = ref([])
const router = useRouter()

// 地址信息（保存在本地）
const address = ref({ name: '', phone: '', detail: '' })
const addrDialogVisible = ref(false)
const addressForm = ref({ name: '', phone: '', detail: '' })
const paymentMethod = ref('wechat')
const payDialogVisible = ref(false)
const paymentMethodDialog = ref('wechat')

const load = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      alert('请先登录查看订单')
      window.location.href = '/login'
      return
    }
    const res = await fetch('/api/orders/', {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    })
    if (!res.ok) {
      const text = await res.text()
      throw new Error(`获取订单失败 [${res.status}] ${text}`)
    }
    orders.value = await res.json()
    // 加载收货地址
    const saved = localStorage.getItem('address')
    if (saved) {
      try { address.value = JSON.parse(saved) } catch {}
    }
  } catch (e) {
    alert(e.message || '加载失败')
  } finally {
    loading.value = false
  }
}

onMounted(load)
// ============ 倒计时（与后端10分钟清理保持一致） ============
const nowTs = ref(Date.now())
let timer = null
onMounted(() => {
  timer = setInterval(() => {
    nowTs.value = Date.now()
  }, 1000)
})
onUnmounted(() => {
  if (timer) clearInterval(timer)
})

const getRemaining = (od) => {
  // 未支付订单从创建时间起10分钟倒计时
  const TEN_MIN_MS = 10 * 60 * 1000
  const created = new Date(od.created_at).getTime()
  const remainMs = Math.max(0, TEN_MIN_MS - (nowTs.value - created))
  if (od.status === 0 && remainMs === 0) {
    // 自动删除（只触发一次）
    tryAutoDelete(od)
  }
  const s = Math.floor(remainMs / 1000)
  const mm = String(Math.floor(s / 60)).padStart(2, '0')
  const ss = String(s % 60).padStart(2, '0')
  return `${mm}:${ss}`
}

const autoDeletingNos = ref(new Set())
const tryAutoDelete = async (od) => {
  if (autoDeletingNos.value.has(od.order_no)) return
  autoDeletingNos.value.add(od.order_no)
  try {
    const token = localStorage.getItem('token')
    const res = await fetch(`/api/orders/${od.order_no}`, {
      method: 'DELETE',
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    })
    // 删除成功或404都刷新列表（考虑后端定时任务已清理）
    if (res.ok || res.status === 404) {
      await load()
    }
  } catch (e) {
    // 忽略错误，下一轮tick会再次尝试，或由后端定时器清理
  } finally {
    autoDeletingNos.value.delete(od.order_no)
  }
}

const selectedTotal = computed(() => {
  const set = new Set(selectedNos.value)
  const sum = orders.value
    .filter(o => set.has(o.order_no))
    .reduce((s, o) => s + Number(o.total_amount), 0)
  return sum.toFixed(2)
})
const selectedItemsCount = computed(() => {
  const set = new Set(selectedNos.value)
  return orders.value
    .filter(o => set.has(o.order_no))
    .reduce((cnt, o) => cnt + o.items.reduce((s, i) => s + Number(i.qty), 0), 0)
})

const openAddressDialog = () => {
  addressForm.value = { ...address.value }
  addrDialogVisible.value = true
}
const saveAddress = () => {
  address.value = { ...addressForm.value }
  localStorage.setItem('address', JSON.stringify(address.value))
  addrDialogVisible.value = false
}

const submitSelected = () => {
  if (selectedNos.value.length === 0) {
    alert('请先选择要结算的订单')
    return
  }
  if (!address.value.name || !address.value.detail) {
    alert('请先填写收货地址')
    openAddressDialog()
    return
  }
  // 打开支付确认弹窗
  paymentMethodDialog.value = paymentMethod.value
  payDialogVisible.value = true
}

const confirmPay = async () => {
  const methodText = paymentMethodDialog.value === 'wechat' ? '微信' : '支付宝'
  
  // 如果是支付宝支付，需要先创建订单
  if (paymentMethodDialog.value === 'alipay') {
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        alert('请先登录')
        router.push('/login')
        return
      }
      
      // 获取选中的订单项
      const selectedItems = []
      for (const orderNo of selectedNos.value) {
        const order = orders.value.find(o => o.order_no === orderNo)
        if (order) {
          for (const item of order.items) {
            selectedItems.push({
              goods_id: item.goods_id,
              name: item.name,
              price: item.price,
              qty: item.qty,
              image_url: item.image_url
            })
          }
        }
      }
      
      if (selectedItems.length === 0) {
        alert('请选择要支付的商品')
        return
      }
      
      // 创建订单
      const response = await fetch('/api/orders/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          items: selectedItems
        })
      })
      
      const result = await response.json()
      if (!response.ok) {
        throw new Error(result.detail || '创建订单失败')
      }
      
      // 跳转到支付页
      router.push({
        path: '/pay',
        query: {
          amount: selectedTotal.value,
          method: paymentMethodDialog.value,
          orderNo: result.order_no
        }
      })
    } catch (error) {
      console.error('创建订单失败:', error)
      // 更详细地显示错误信息
      let errorMsg = '创建订单失败'
      if (error instanceof Error) {
        errorMsg = error.message
      } else if (typeof error === 'object' && error !== null) {
        errorMsg = JSON.stringify(error)
      }
      alert(errorMsg)
      return
    }
  } else {
    // 微信支付或者其他支付方式
    router.push({
      path: '/pay',
      query: {
        amount: selectedTotal.value,
        method: paymentMethodDialog.value,
        items: String(selectedItemsCount.value)
      }
    })
  }
  
  // 关闭弹窗
  payDialogVisible.value = false
  paymentMethod.value = paymentMethodDialog.value
}

// 新增方法：跳转到创建订单页面
const goToCreateOrder = () => {
  router.push('/create-order')
}

// 新增方法：跳转到测试页面
const goToTestPage = () => {
  router.push('/order-test')
}

// 新增方法：测试RabbitMQ连接
const testRabbitMQ = async () => {
  try {
    const result = await orderService.testConnection()
    if (result.code === 200) {
      alert(`RabbitMQ连接测试成功！\n主机: ${result.data.host}\n端口: ${result.data.port}\n队列: ${result.data.queue}`)
    } else {
      alert('RabbitMQ连接测试失败：' + result.message)
    }
  } catch (error) {
    alert('RabbitMQ连接测试失败：' + error.message)
  }
}

// 新增方法：查询订单状态
const checkOrderStatus = async (orderNo) => {
  try {
    const result = await orderService.getOrderStatus(orderNo)
    if (result.code === 200) {
      alert(`订单状态查询成功！\n订单号: ${result.data.order_no}\n状态: ${result.data.status}\n消息: ${result.data.message}`)
    } else {
      alert('订单状态查询失败：' + result.message)
    }
  } catch (error) {
    alert('订单状态查询失败：' + error.message)
  }
}
</script>

<style scoped>
.orders-container { width:100vw; min-height:100vh; background:#f7f7f7; }
.header { position:sticky; top:0; background:#fff; padding:12px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center; }
.title { font-weight:700; }
.header-actions { display:flex; gap:8px; }
.create-order-btn { background:#007bff; color:#fff; border:none; padding:6px 12px; border-radius:4px; font-size:12px; cursor:pointer; }
.test-rabbitmq-btn { background:#28a745; color:#fff; border:none; padding:6px 12px; border-radius:4px; font-size:12px; cursor:pointer; }
.test-page-btn { background:#6f42c1; color:#fff; border:none; padding:6px 12px; border-radius:4px; font-size:12px; cursor:pointer; }
.create-order-btn:hover { background:#0056b3; }
.test-rabbitmq-btn:hover { background:#218838; }
.test-page-btn:hover { background:#5a32a3; }
.hint { padding:20px; color:#666; }
.list { padding:10px; display:flex; flex-direction:column; gap:12px; }
.order { background:#fff; border-radius:8px; overflow:hidden; }
.order-head { display:flex; justify-content:space-between; align-items:center; gap:10px; padding:10px 12px; border-bottom:1px solid #eee; }
.order-head .countdown { color:#ff4757; font-size:12px; }
.items { padding:8px 12px; display:flex; flex-direction:column; gap:8px; }
.item { display:flex; gap:10px; }
.cover { width:60px; height:60px; object-fit:cover; background:#eee; border-radius:6px; }
.meta { flex:1; display:flex; flex-direction:column; justify-content:space-between; }
.row { display:flex; justify-content:space-between; color:#666; }
.order-foot { padding:8px 12px; border-top:1px solid #eee; color:#999; font-size:12px; }

/* 地址卡片 */
.address-card { display:flex; justify-content:space-between; gap:10px; padding:12px; margin:10px; background:#fff; border-radius:8px; border:1px solid #eee; align-items:center; cursor:pointer; }
.addr-left .row { margin:2px 0; }
.addr-left .row.small { color:#666; font-size:12px; }
.addr-left .label { color:#999; margin-right:8px; }
.addr-right { color:#999; }
.phone { margin-left:8px; color:#666; }

/* 选择框 */
.check { display:flex; align-items:center; }
.check input { display:none; }
.check .fake { width:16px; height:16px; border:1px solid #ccc; border-radius:50%; display:inline-block; margin-right:6px; position:relative; }
.check input:checked + .fake::after { content:''; position:absolute; left:3px; top:3px; width:8px; height:8px; border-radius:50%; background:#ff4757; }

/* 底部结算条 */
.settle-bar { position:fixed; left:0; right:0; bottom:0; background:#fff; border-top:1px solid #eee; padding:10px; display:flex; justify-content:space-between; align-items:center; }
.submit-btn { background:#ff4757; color:#fff; border:none; border-radius:20px; padding:10px 18px; font-weight:700; }

/* 弹窗 */
.dialog-mask { position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000; }
.dialog { width:90%; max-width:420px; background:#fff; border-radius:10px; overflow:hidden; }
.dialog-title { font-weight:700; padding:12px; border-bottom:1px solid #eee; }
.dialog-body { padding:12px; display:flex; flex-direction:column; gap:12px; }
.form-row { display:flex; align-items:center; gap:10px; }
.form-row label { width:70px; color:#666; }
.form-row input, .form-row textarea { flex:1; border:1px solid #ddd; border-radius:6px; padding:8px; }
.dialog-actions { padding:10px; display:flex; justify-content:flex-end; gap:10px; border-top:1px solid #eee; }
.btn { border:1px solid #ddd; background:#fff; border-radius:6px; padding:8px 12px; }
.btn.primary { background:#ff4757; color:#fff; border-color:#ff4757; }

/* 面板与支付方式 */
.panel { background:#fff; margin:10px; border-radius:8px; border:1px solid #eee; overflow:hidden; }
.panel-head { padding:12px; display:flex; justify-content:space-between; border-bottom:1px solid #f3f3f3; }
.gray { color:#888; font-size:12px; }
.pay-row { padding:12px; border-top:1px solid #f6f6f6; }
.radio { display:flex; align-items:center; gap:8px; }
.radio input { display:none; }
.radio .dot { width:16px; height:16px; border:1px solid #ccc; border-radius:50%; position:relative; display:inline-block; }
.radio input:checked + .dot::after { content:''; position:absolute; left:3px; top:3px; width:8px; height:8px; border-radius:50%; background:#ff4757; }

/* 支付确认弹窗补充样式 */
.summary-row { display:flex; justify-content:space-between; padding:6px 0; }
.summary-row.small { color:#666; font-size:12px; }
</style>


